package com.srxz.personnelsystem.system.service.impl;

import com.srxz.personnelsystem.system.entity.LoginInfo;
import com.srxz.personnelsystem.system.entity.UserInfo;
import com.srxz.personnelsystem.system.mapper.converter.LoginInfoMapper;
import com.srxz.personnelsystem.system.mapper.converter.UserInfoMapper;
import com.srxz.personnelsystem.system.mapper.dto.LoginInfoDTO;
import com.srxz.personnelsystem.system.mapper.dto.UserInfoDTO;
import com.srxz.personnelsystem.system.repository.LoginInfoRepository;
import com.srxz.personnelsystem.system.repository.UserInfoRepository;
import com.srxz.personnelsystem.system.service.UserService;
import com.srxz.personnelsystem.system.service.mapimpl.UserMapperServiceImpl;
import com.srxz.personnelsystem.util.BackMessage;
import com.srxz.personnelsystem.util.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.persistence.criteria.*;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: UserServiceImpl
 * @author: wgchao
 * @createTime: 2019/1/23 10:22 AM
 * @Description: TODO
 */
@Service
@Transactional
public class UserServiceImpl extends UserMapperServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private LoginInfoRepository loginInfoRepository;

    @Override
    public BackMessage save(UserInfoDTO userInfoDTO) {
        System.out.println(userInfoDTO.getDepartmentId());
        //检查身份证号是否已存在
        UserInfo userInfo1 = userInfoRepository.findFirstByIdcardAndDeleteTimeIsNull(userInfoDTO.getIdcard());
        if(userInfo1 != null){
            return BackMessage.error("身份证号已被使用，请检查确认");
        }

        UserInfo userInfo = userInfoMapper.entity(userInfoDTO);
        if(userInfo.getLogin() == null){
            userInfo.setLogin(false);
        }
        userInfo.setStatus(0);
        if(userInfo.getRegularTime() != null){//转正
            userInfo.setStatus(1);
        }
        userInfo.setCreateTime(new Date());
        //TODO 添加创建人 ---
        System.out.println(userInfo.getDepartmentId());
        userInfo = userInfoRepository.save(userInfo);
        LoginInfoDTO loginInfoDTO = userInfoDTO.getLoginInfoDTO();
        userInfoDTO = userInfoMapper.dto(userInfo);
        extendCommon(userInfoDTO);

        //如果用户可登陆 保存登陆账户信息
//        if(userInfo.getLogin() && loginInfoDTO!=null){
//            LoginInfo loginInfo = loginInfoMapper.entity(loginInfoDTO);
//            loginInfo.setPassword(DigestUtils.md5DigestAsHex(loginInfo.getPassword().getBytes()));
//            loginInfo.setUserId(userInfo.getId());
//            loginInfo.setStatus(true);
//            loginInfo = loginInfoRepository.save(loginInfo);
//            userInfoDTO.setLoginInfoDTO(loginInfoMapper.dto(loginInfo));
//        }

        return BackMessage.success().putData("user", userInfoDTO);
    }

    @Override
    public BackMessage delete(UserInfoDTO userInfoDTO) {

        UserInfo userInfo = userInfoRepository.getOne(userInfoDTO.getId());
        if(userInfo != null){
         //   userInfo.setStatus(true);

            userInfo.setDeleteTime(new Date());
            userInfo.setLastUpdateTime(new Date());
            //TODO 添加删除、更新人

            userInfo = userInfoRepository.save(userInfo);
            userInfoDTO = userInfoMapper.dto(userInfo);

            /************** 删除登陆账户 *
            if(userInfo.getLogin()){
                List<LoginInfo> loginInfos = loginInfoRepository.findAllByUserIdAndDeleteTimeIsNullAndStatusIsTrue(userInfo.getId());
                if(!loginInfos.isEmpty()){
                    for(LoginInfo loginInfo:loginInfos){
                        loginInfo.setDeleteTime(new Date());
                        loginInfo.setLastUpdateTime(new Date());
                        //TODO 添加删除、更新人

                        loginInfo = loginInfoRepository.save(loginInfo);
                    }
                }
            }
             *************/

        }
        return BackMessage.success().putData("user", userInfoDTO);
    }

    public BackMessage deletelist(List<UserInfoDTO> userInfoDTOs) {
        for(UserInfoDTO userInfoDTO:userInfoDTOs){
            UserInfo userInfo = userInfoRepository.getOne(userInfoDTO.getId());
            if(userInfo != null){
                //   userInfo.setStatus(true);

                userInfo.setDeleteTime(new Date());
                userInfo.setLastUpdateTime(new Date());
                //TODO 添加删除、更新人

                userInfo = userInfoRepository.save(userInfo);
                userInfoDTO = userInfoMapper.dto(userInfo);

                /************** 删除登陆账户
                if(userInfo.getLogin()){
                    List<LoginInfo> loginInfos = loginInfoRepository.findAllByUserIdAndDeleteTimeIsNullAndStatusIsTrue(userInfo.getId());
                    if(!loginInfos.isEmpty()){
                        for(LoginInfo loginInfo:loginInfos){
                            loginInfo.setDeleteTime(new Date());
                            loginInfo.setLastUpdateTime(new Date());
                            //TODO 添加删除、更新人

                            loginInfo = loginInfoRepository.save(loginInfo);
                        }
                    }
                }**************/

            }
        }

        return BackMessage.success();
    }

    @Override
    public BackMessage update(UserInfoDTO userInfoDTO) {

        UserInfo userInfo = userInfoMapper.entity(userInfoDTO);
        if(userInfo.getRegularTime() != null && userInfo.getStatus()!=-1){//转正
            userInfo.setStatus(1);
        }
        userInfo.setLastUpdateTime(new Date());
        //TODO 添加更新人

        userInfo = userInfoRepository.save(userInfo);
        userInfoDTO = userInfoMapper.dto(userInfo);

        if(userInfo.getLogin()!=null && !userInfo.getLogin()){
            List<LoginInfo> loginInfos = loginInfoRepository.findAllByUserIdAndDeleteTimeIsNullAndStatusIsTrue(userInfo.getId());
            if(!loginInfos.isEmpty()){
                for(LoginInfo loginInfo:loginInfos){
                    loginInfo.setDeleteTime(new Date());
                    loginInfo.setLastUpdateTime(new Date());
                    //TODO 添加删除、更新人

                    loginInfo = loginInfoRepository.save(loginInfo);
                }
            }
        }

        return BackMessage.success().putData("user", userInfoDTO);
    }

    @Override
    public BackMessage search(String userId) {
        UserInfo userInfo = userInfoRepository.getOne(userId);
        UserInfoDTO userInfoDTO = userInfoMapper.dto(userInfo);
        extendCommon(userInfoDTO);
        extendLoginInfoDTO(userInfoDTO);

        return BackMessage.success().putData("user", userInfoDTO);
    }

    @Override
    public BackMessage searchToPage(PageParam pageParam) {
        Pageable pageable = PageRequest.of(pageParam.getCurrPage(), pageParam.getLimit());

        Specification<UserInfo> dispatchSpecification = new Specification<UserInfo>() {
                @Override
                public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    //设置查询条件
                    List<Predicate> list = new ArrayList<Predicate>();
                    if (pageParam.getSearchCon() != null && !pageParam.getSearchCon().isEmpty()) {
                        for (Map.Entry<String, Object> km : pageParam.getSearchCon().entrySet()) {
                            String key = km.getKey();
                            Object val = km.getValue();
                            if ("con".equals(key)) {//用户姓名或者身份证号
                                if (val == null || val.toString().equals("")) {
                                    continue;
                                }
                                Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%" + km.getValue().toString() + "%");
                                Predicate p2 = criteriaBuilder.like(root.get("idcard").as(String.class), "%" + km.getValue().toString() + "%");
                                Predicate p = criteriaBuilder.or(p1, p2);
                                list.add(p);
                            } else if ("login".equals(key)) {//过滤可登陆用户
                                if (val == null || val.toString().equals("")) {
                                    continue;
                                }
                                Predicate p = criteriaBuilder.equal(root.get("name").as(String.class), Boolean.valueOf(km.getValue().toString()));
                                list.add(p);
                            } else if ("status".equals(key)) {//过滤停用用户
                                if (val == null || val.toString().equals("")) {
                                    continue;
                                }
                                Predicate p = criteriaBuilder.equal(root.get("status").as(Integer.class), km.getValue().toString());
                                list.add(p);
                            }
                        }
                    }
                    //未删除
                    Predicate p1 = criteriaBuilder.isNull(root.get("deleteTime").as(ZonedDateTime.class));
                    list.add(p1);

                    return criteriaBuilder.and(list.toArray(new Predicate[0]));
                }
            };

        //执行查询操作
        Page<UserInfo> userInfos = userInfoRepository.findAll(dispatchSpecification, pageable);
        List<UserInfoDTO> userInfoDTOS = userInfos.getContent().stream().
                map(n -> {
                    UserInfoDTO userInfoDTO = userInfoMapper.dto(n);
                    extendCommon(userInfoDTO);
                    extendExtraInfoDTO(userInfoDTO);
                    extendDepartmentName(userInfoDTO);
                    return userInfoDTO;
                }).collect(Collectors.toList());
        return BackMessage.success().putPageData(userInfos.getTotalElements(), userInfoDTOS);
    }
}
